/********************************************************/
/*	Copyright (C) 2016 Gong Li Bin			*/
/*	Project:	GlbKv-1.0.0			*/
/*	Author:		gong_libin			*/
/*	Date:		2013_10_11			*/
/*	File:		GlbKvInput.cpp			*/
/********************************************************/

#include "GlbKv.h"

int main(int argc, char* argv[])
{
	UINT uiTimeout = 0;
	GlbNet::CGlbUdp CUdp;
	GlbNet::CGlbPro CSend;
	GlbNet::CGlbPro CRecv;
	GlbCls::CGlbFile CFile;
	time_t ulTime = time(NULL);
	char szKey[GLB_BYTE128] = { 0 };
	UCHAR uszSend[GLB_KBYTES8] = { 0 };
	UCHAR uszRecv[GLB_KBYTES8] = { 0 };
	UCHAR uszPacket[GLB_KBYTES8] = { 0 };
	GlbNet::GLBPROKV_S stKv[GLB_KV_PAIR] = {{GLB_KV_KEY, 0, (UCHAR*)szKey}, {GLB_KV_VAL, 0, NULL}};
	GlbNet::GLBPROHEAD_S stHead = {
		GLB_PRO_FLAG,
		GLB_PRO_1,
		GLB_PRO_DATA,
		GLB_PRO_0,
		GLB_PRO_Y,
		GLB_PRO_0,
		GLB_PRO_0,
		GLB_DEF_INST,
		GLB_PRO_0,
		GLB_DEF_SUCC,
		GLB_KV_PAIR,
		GLB_PRO_0,
	};

	if (argc < 3) {
		GLB_PRINT("Usage: %s %s%s.xxx port\n", argv[0], GLB_KV_PATH, GLB_KV_FILE);
		return GLB_SUCCESS;
	}

	CSend.GlbProPutBody(NULL);
	CSend.GlbProInduce(&stHead);

	if (GLB_SUCCESS == CUdp.GlbNetInitSend(const_cast<char*>("127.0.0.1"), const_cast<char*>(argv[2]))) {
		CUdp.GlbNetSetTimeOut(GLB_TIMEOUT, 0);
		if (GLB_SUCCESS == CFile.GlbFileOpen(argv[1], GLB_O_RDONLY)) {
			/* time */
			CFile.GlbFileRead((UCHAR*)&uiTimeout, GLB_KV_INT, false);
			/* leng */
			while (CFile.GlbFileRead(uszPacket, GLB_KV_INT, false) > 0) {
				/* data */
				if (CFile.GlbFileRead(uszPacket + GLB_KV_INT, GLB_KV_ULL + GLB_KV_TIM + *(int*)uszPacket, false) > 0) {
					if (static_cast<UINT>(ulTime - *(time_t*)(uszPacket + GLB_KV_INT + GLB_KV_ULL)) < uiTimeout) {
						/* key */
						sprintf(szKey, "%llu", *(ULONGLONG*)(uszPacket + GLB_KV_INT));
						stKv[0].m_iLength = strlen(szKey);
						/* val */
						stKv[1].m_puszValue = uszPacket + GLB_KV_OFF;
						stKv[1].m_iLength = *(int*)uszPacket;
						/* pkt */
						CSend.GlbProPutLength(GlbProKvOutput(stKv, GLB_KV_PAIR, &uszSend[GLB_PRO_HEAD], GLB_KBYTES8));
						CSend.GlbProCreate(uszSend, GLB_KBYTES8);
						/* send */
						if (CUdp.GlbNetSend(uszSend, GLB_PRO_HEAD + CSend.GlbProGetLength()) > 0) {
							if ((CUdp.GlbNetRecv(uszRecv, GLB_KBYTES8)) > 0) {
								CRecv.GlbProReset();
								CRecv.GlbProParse(uszRecv, GLB_PRO_HEAD);
								if (GLB_DEF_SUCC == CRecv.GlbProGetResult()) {
									GLB_PRINT("Result[%s]: success\n", szKey);
								}
								else {
									GLB_PRINT("Result[%s]: failure\n", szKey);
								}
							}
							else {
								GLB_PRINT("Result[%s]: failure\n", szKey);
							}
						}
						else {
							GLB_PRINT("Result[%s]: failure\n", szKey);
						}
					}
				}
				memset(uszPacket, '\0', GLB_KBYTES8);
				memset(szKey, '\0', GLB_BYTE128);
			}
			CFile.GlbFileClose();
		}
		CUdp.GlbNetClose();
	}
	
	return GLB_SUCCESS;
}
